import java.util.HashMap;
import java.util.Map;

/**
 * \* Created with IntelliJ IDEA.
 * \* User: 冯若航
 * \* Date: 2021/6/9
 * \* Time: 17:31
 * \* To change this template use File | Settings | File Templates.
 * \* Description:
 * \
 */
public class 字符串的排列 {
    public boolean checkInclusion(String s1, String s2) {
        if(s2.length()<s1.length()){return false;}
        Map<Character, Integer> need=new HashMap<>();
        Map<Character, Integer> window=new HashMap<>();
        for(char c:s1.toCharArray()){
            need.put(c, need.getOrDefault(c,0)+1);
        }
        int left=0,right=0,valid=0;
        while(right<s2.length()){
            char c= s2.charAt(right);
            right++;
            if(need.containsKey(c)){
                window.put(c,window.getOrDefault(c,0)+1);
                if(window.get(c).equals(need.get(c))){
                    valid++;
                }
            }

            // 判断左侧窗口是否要收缩
            while (right-left>=s1.length()){
                // 在这里判断是否找到了合法的子串
                if(valid==need.size()){
                    return true;
                }
                char d=s2.charAt(left);
                left++;
                // 进行窗口内数据的一系列更新
                if(need.containsKey(d)){
                    if(window.get(d).equals(need.get(d))){
                        valid--;
                    }
                    window.put(d, window.getOrDefault(d,0)-1);
                }
            }
        }
        return false;
    }
}